package dao.impl;

import dao.UserDao;
import domain.User;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import util.JDBCUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class UserDaoImpl implements UserDao {
    private JdbcTemplate template=new JdbcTemplate(JDBCUtils.getDataSourse());

    @Override
    public List<User> findAll() {
        String sql="select * from user";
        List<User> list=template.query(sql,new BeanPropertyRowMapper<>(User.class));
        return list;
    }

    @Override
    public User findById(int id) {
        String sql="select * from user where id=?";
        return template.queryForObject(sql,new BeanPropertyRowMapper<>(User.class),id);
    }

    @Override
    public void delete(int id) {
        String sql="delete from user where id=?";
        template.update(sql,id);
    }

    @Override
    public void add(User user) {
        String sql="insert into user values(null,?,?,?,?,?,?,null,null)";
        template.update(sql,user.getName(),user.getGender(),user.getAge(),user.getAddress(),user.getQq(),user.getEmail());
    }

    @Override
    public void update(User user) {
        String sql="update user set name=?,gender=?,,age=?,address=?,qq=?,email=? where id=?";
        template.update(sql,user.getName(),user.getGender(),user.getAge(),user.getAddress(),user.getQq(),user.getEmail(),user.getId());
    }

    @Override
    public User findUsernameAndPassword(String username, String password) {
        try{
            String sql="select * from user where username=? and password=?";
            User user=template.queryForObject(sql,new BeanPropertyRowMapper<>(User.class),username,password);
            return user;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public List<User> findSelected(User user) {
        String sql="select * from user where 1=1 ";
        ArrayList arr=new ArrayList();
        if(user.getName()!=null && user.getName().length()>0){
            sql+="and name like ?";
            arr.add('%'+user.getName()+'%');
        }
        if(user.getAddress()!=null && user.getAddress().length()>0){
            sql+="and address like ?";
            arr.add('%'+user.getAddress()+'%');
        }
        if(user.getEmail()!=null && user.getEmail().length()>0){
            sql+="and email like ?";
            arr.add('%'+user.getEmail()+'%');
        }
        List<User> list =template.query(sql,new BeanPropertyRowMapper<>(User.class),arr.toArray());
        return list;
    }
}
